<?php
//命名空间
namespace Shop\Controller;
//使用命名空间 引入空间里面的类
use Shop\Controller\BaseController;

class UserController extends BaseController {
	
	private $userModel;
	private $nologin=array('loginOut','step2');
	public  function  __construct()
	{
		parent::__construct();
		$this->userModel=M('user');
		if(!in_array(ACTION_NAME,$this->nologin)){
			if(session("?userinfo")&& IS_LOGIN)
			{
				$this->success('您已经登录',U('Index/index'),1000);
				exit;
			}
		}
	}
	
    public function index(){
    	$this->view("index");
    }
    
    
    
    
    
    
    
    
  /**
   * QQ第三方登录
   */  
    public function qqlogin(){
    	$code=I('get.code');
    	
    	//应用的APPID
    	$app_id = "101188123";
    	//应用的APPKEY
    	$app_secret = "33e7d8590ff78e4b2e072b30b4156851";
    	//成功授权后的回调地址
    	$my_url = "yu.oschina.mopaas.com/index.php/Shop/User/qqlogin";
    	
    	//Step1：获取Authorization Code
    	$code = $_REQUEST["code"];
    	if(empty($code))
    	{
    		//state参数用于防止CSRF攻击，成功授权后回调时会原样带回
    		$_SESSION['state'] = md5(uniqid(rand(), TRUE));
    		//拼接URL
    		$dialog_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
    				. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
    						. $_SESSION['state'];
    		echo("<script> top.location.href='" . $dialog_url . "'</script>");
    	}

    	//Step2：通过Authorization Code获取Access Token
    	if($_REQUEST['state'] == $_SESSION['state'])
    	{
    		//拼接URL
    		$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
    				. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
    				. "&client_secret=" . $app_secret . "&code=" . $code;
    		$response = file_get_contents($token_url);
    		if (strpos($response, "callback") !== false)
    		{
    			$lpos = strpos($response, "(");
    			$rpos = strrpos($response, ")");
    			$response  = substr($response, $lpos + 1, $rpos - $lpos -1);
    			$msg = json_decode($response);

    			if (isset($msg->error))
    			{
    				echo "<h3>error:</h3>" . $msg->error;
    				echo "<h3>msg  :</h3>" . $msg->error_description;
    				exit;
    			}
    		}
    	
    		//Step3：使用Access Token来获取用户的OpenID
    		$params = array();
    		parse_str($response, $params);
    		$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token'];
    		$str  = file_get_contents($graph_url);
    		if (strpos($str, "callback") !== false)
    		{
    			$lpos = strpos($str, "(");
    			$rpos = strrpos($str, ")");
    			$str  = substr($str, $lpos + 1, $rpos - $lpos -1);
    		}
    		$user = json_decode($str);
    		if (isset($user->error))
    		{
    			echo "<h3>error:</h3>" . $user->error;
    			echo "<h3>msg  :</h3>" . $user->error_description;
    			exit;
    		}
    		//echo("Hello " . $user->openid);
    		
    		
    		$this->qqlogin2($params['access_token'],$app_id,$user->openid);
    		
    	



    	}
    	else
    	{
    		echo("The state does not match. You may be a victim of CSRF.");
    	}
    }
    
    
    
    
    
    
    
    public function qqlogin2($access_token,$app_id,$openid){	
    	header("Content-type: text/html; charset=utf-8");
    		//Step4：使用OpenID来获取用户的用户资料
    		$graph_url = "https://graph.qq.com/user/get_user_info?access_token=".$access_token."&oauth_consumer_key=".$app_id."&openid=".$openid;
    		$qqinfostr = file_get_contents($graph_url);
    		
    		$userinfo  = json_decode($qqinfostr);
    		
    		if ($userinfo->ret!=0)
    		{
    			print_r("<h3>error:</h3>". $userinfo->msg);
    			exit;
    		}
    		

$this->assign('userallinfo',$qqinfostr);
$this->assign('openid',$openid);
$this->assign('userinfo',$userinfo);
$this->view("login");
    		
    	
    	
    }
    
    
	
	
	
	
	
	
	
	
	
     
    /**
	 *微博登录
	 */
    public function weibologin(){
		include_once( './Api/sina/config.php' );
		include_once( './Api/sina/saetv2.ex.class.php' );
		
		$o = new \SaeTOAuthV2( WB_AKEY , WB_SKEY );

		$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
		
		echo("<script> top.location.href='" . $code_url . "'</script>");
		
    }
  
	

	
	
	
	
	
	
	public function weibocallback(){

		include_once( './Api/sina/callback.php' );
		
	}
	
	
	
	
	
	
	
    
    
    //会员登录
    Public function login(){
    
    	//验证是否有POST提交
    	if(!empty($_POST)){
    		//第一步：接收数据，并赋值变量
    		$username = $_POST['username'];
    		$password = $_POST['password'];
    		$remember = isset($_POST['remember']) ? 1 : 0;
    
    		//第二步：验证数据格式是否正确
    		if(empty($username) || empty($password)){
    			$this->error('用户名或密码不能为空！');
    		}
    			
    		//第三步：使用$username 读取数据，病判断$username是否存在
    		$row  = M('user')->where("`email`= '{$username}' or `phone`= '{$username}'")->find();
    		if($row === null)$this->error('用户名不存在！');
    		
    		//第四步：验证加密后的密码是否正确
    		//echo md5(md5($password) . $row['key']);exit;
    		if($row['password'] == md5($password)){
    			if($row['password'] === 0)$this->error('该账户没有激活，请到邮箱' . $row['email'] . '激活！');
    
    			//第五步：记录登录信息
    			$_SESSION['member'] = array(
    					'id' => $row['id'],
    					'email' => $row['email'],
    					'username' => $row['username'],
    					'phone' => $row['phone']
    						
    			);
    			//判断是否需要记住密码
    			if($remember){
    				$time = time() + 7 * 3600;
    				setcookie('email', $row['email'], $time);
    				setcookie('password', $row['password'], $time);
    			}
    			if(isset($_SESSION['fromUrl'])){
    				$this->success('登陆成功', $_SESSION['fromUrl']);
    			}else{
    				$this->success('登陆成功', __CONTROLLER__ . '.html');
    			}
    		}else{
    				
    			$this->error('密码错误，登录失败!');
    		}
    		exit;
    	}
    	//print_r($_SERVER);exit;
    	$fromUrl = $_SERVER['HTTP_REFERER'];
    	if(stripos($fromUrl, 'goods') != false && stripos($fromUrl, 'info') != false){
    		$_SESSION['fromUrl'] = $fromUrl;
    	}else{
    		unset($_SESSION['fromUrl']);
    	}
    	$this->view();
    }
    
    
    
    public function loginOut()
    {
    	session("member",null);
    	$this->success('退出成功！！',U('User/login'),1000);
    	exit;
    }
    
    
    /**
     * 注册用户
     */
    public function register()
    {
    	$userModel=M('user');
    	
		if(!empty($_POST))
		{	
			$ismail=$userModel->where('email="'.I('post.email').'"')->find();
			if(!empty($ismail))
			{
				$this->error("该邮箱已经被注册！！");
				exit;
			}
			$roundkey=randomkeys();   //返回PHP随机字符串的代码
			$reUser=array(
				'username'=>I('post.username'),
				'password'=>md5(I('post.password')),
				'email'=>I('post.email'),
				'relive'=>$roundkey,   //返回PHP随机字符串的代码
			);
			$userModel->add($reUser);
			$emailadd=I('post.email');
			$emailname=I('post.username');
			$mailContent=' if you are thinking about moving to premium '.'<a href="'.'__ROOT__'.'/index.php/shop/user/relive?name='.I('post.email').'&relive='.$roundkey.'">shop relive</a>';
			$sendmail=sendMail($emailadd,$emailname,' if you are thinking about moving to premium ',$mailContent);//发送邮件
			$this->success('注册成功 请前往邮箱激活账户！！',U('User/login'),1000);
			exit();
			if($sendmail=='success')
			{
				$this->success('注册成功 请前往邮箱激活账户！！',U('User/login'),1000);
				exit;
			}
		}
		$this->assign("step","register");    
    	$this->view('register');
    
    }
    
    /*
     * 接收邮件
     * 客户发送数据到这里进行验证邮箱
     * PHP随机字符串的代码   用于验证邮箱
     */
    public function relive()
    {
    	$useremail=I('get.name');
    	$userrelive=I('get.relive');
    	$data=array();
    	$data['statue']='1';
    	$reaf=$this->userModel->where('relive="'.$userrelive.'" and email="'.$useremail.'"')->save($data);
    	if($reaf>0)
    	{
    		$userinfo=$this->userModel->where('email="'.$useremail.'"')->find();
    		session('userinfo',$userinfo);
    		define("IS_LOGIN", true);
    		$this->success('激活成功！！',U('User/step2'),1000);exit;
    	}
    	else{
    	    $this->error('激活失败！！',U('User/register'),1000);exit;
    		
    	}
    }
    public function step2()
    {
    	
    	if(!empty($_POST))
    	{
    		$userinfo=session("userinfo");
    		$_POST['user_id']=$userinfo['id'];
    		M('user_info')->add($_POST);
    		$this->success('注册成功过！！',U('User/index'),1000);
    		exit;
    	}
    	$this->assign("step",'step2');
    	$this->view("register");
    }
    
   
    
   
    
}